import Api from '../../utils/person'
const db = wx.cloud.database()
let adminopenid = 'o4rZq5GUQ4syqiU4xvTF4feBIGmc' //管理员的openid
Page({
  data:{
    isLogin:false,//判断是否登录
    userInfo:null,//存储用户信息，包括用户头像和昵称
    currentUserPbRecipes:[], //当前用户发布的菜谱
    page:1,//当前用户发布的菜谱的当前页码
    pagesize:4,//每页显示3条
    isMore:true,//默认有下一页
    currentUserPtTypes:[],//获取当前用户往哪个菜谱分类下发布的信息
    activeIndex:0,//选项卡下标
    currentUserFllowRecipes:[],//当前登录用户关注的菜谱
    fPage:1,//关注的菜谱的当前页码
    fPageSize:3,//关注的菜谱每页显示的条数
  },
  _goToRecipeDetail(e){
    let {id,title} = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/recipeDetail/recipeDetail?id=${id}&title=${title}`,
    })
  },
  async _getCurrentUserFllowRecipe(){//当前登录用户关注的菜谱
    let { _openid } = wx.getStorageSync('userInfo')
    let fPage = this.data.fPage
    let fPageSize = this.data.fPageSize
    let skip = (fPage-1)*fPageSize
    let fllowRecipes = await db.collection('re-fllows').where({
      _openid
    }).limit(fPageSize).skip(skip).get()
    console.log(fllowRecipes)
    let fllowRecipePromises = []
    fllowRecipes.data.forEach(item=>{
      let p = db.collection('re-recipes').doc(item.recipeId).get()
      fllowRecipePromises.push(p)
    })
    let userFllowRecipes = await Promise.all(fllowRecipePromises)
    let currentUserFllowRecipes = userFllowRecipes.map(item=>{
      return item.data
    })
    this.setData({
      currentUserFllowRecipes
    })
  },
  async _doDeleteRecipeById(e){//删除对应用户的菜谱
    let {id,index} = e.currentTarget.dataset
    let delResult = await db.collection('re-recipes').doc(id).update({
      data:{
        status:2
      }
    })
    console.log(delResult)
    this.data.currentUserPbRecipes.splice(index,1)
    this.setData({
      currentUserPbRecipes:this.data.currentUserPbRecipes
    })
  },
  _switchTabHandle(e){
    console.log(e.currentTarget.dataset)
    this.setData({
      activeIndex:e.currentTarget.dataset.index
    })
  },
  async _getCurrentUserPtTypes(){//获取当前用户往哪个菜谱分类下发布的信息
    let {_openid} = wx.getStorageSync('userInfo')
    let results = await db.collection('re-userPbTypes').where({
      _openid
    }).get()
    let typePromises = []
    results.data.forEach(item=>{
      let p = db.collection('re-recipeType').doc(item.recipeTypeId).get()
      typePromises.push(p)
    })
    let typeResult = await Promise.all(typePromises)
    let currentUserPtTypes = typeResult.map(item=>{
      return item.data
    })
    // console.log(currentUserPtTypes)
    this.setData({
      currentUserPtTypes
    })
  },
  // 跳转到菜谱发布页
  _goToPbRecipe(){
    wx.navigateTo({
      url: '/pages/pbmenu/pbmenu',
    })
  },
  onReachBottom(){//滑到底部，下一页
    console.log('下一页')
    let activeIndex = this.data.activeIndex
    switch(activeIndex){
      case 0:
        console.log('菜谱下一页')
        this.data.page++
        this._getCurrentUserPbRecipes()
        break
      case 1:
        console.log('分类下一页')
        break
      case 2:
        console.log('关注下一页')
        break
    }
  },
  // 获取当前当前用户发布的菜谱
  async _getCurrentUserPbRecipes(){
    // console.log(this.data.userInfo)
    let _openid = this.data.userInfo._openid
    if(!this.data.isMore){
      wx.showToast({
        title: '没有更多了',
        icon:'none'
      })
      return
    }
    wx.showLoading({
      title: '正在请求...',
    })

    var pagesize = this.data.pagesize//每页显示3条
    // var page = 1 //当前页
    var skip = (this.data.page-1)*pagesize
    let result = await db.collection('re-recipes').where({
      _openid,
      status:1
    }).limit(pagesize).skip(skip).orderBy('addtime','desc').get()
    // console.log(result)
    wx.hideLoading()
    if(result.data.length == 0){//如果没有0则设置开关关闭
      this.data.isMore = false
    }
    this.setData({
      currentUserPbRecipes:this.data.currentUserPbRecipes.concat(result.data)
    })
  },
  // 根据是否是管理员进入菜谱分类的发布页
  _goToPbRecipeType(){
    // 从缓存中获取当前用户的openid
    let userInfo = wx.getStorageSync('userInfo')
    if(userInfo._openid == adminopenid){
      wx.navigateTo({
        url: '/pages/pbmenutype/pbmenutype',
      })
    }
  },
  onShow(){
    this._isLogin()
    this._getCurrentUserPtTypes()
    this._getCurrentUserFllowRecipe()
  },
  // 进入页面判断是否登录
  _isLogin(){
    let userInfo = wx.getStorageSync('userInfo')
    if(userInfo){
      this.setData({
        isLogin:true,
        userInfo
      })
      this._getCurrentUserPbRecipes()
    }
  },
  // 登录功能
  _doLogin(e){
    // console.log(e)
    let userInfo = e.detail.userInfo
    wx.login({
      success: async ()=>{
        let result = await wx.cloud.callFunction({
          name:'w-login'
        })
        // console.log(result)
        let _openid = result.result.openid
        let data = {
          _openid,
          avatarUrl:userInfo.avatarUrl,
          nickName:userInfo.nickName
        }

        wx.setStorageSync('userInfo', data)

        // 判断，re-users表中有无此用户
        let user = await db.collection('re-users').where({
          _openid
        }).get()
          delete data._openid
          if(user.data.length ==1){
          console.log("更新操作")
          db.collection('re-users').where({
            _openid
          }).update({
            data
          })
        }else{
          console.log("添加操作")
          db.collection('re-users').add({
            data
          })
        }
      //  return
      data._openid = _openid
        this.setData({
          isLogin:true,
          userInfo:data
        })
        this._getCurrentUserPbRecipes()//登录成功调用用户发布的菜谱

      }
    })
  },

})